$(function() {
	preload(start);
});

function start() {

	init();
}

function init() {

	create();

	attach();

	first();

	function create() {
		// 标签包
		createBagSel();

		// 是否冻结
		createStatusSel();

		// 表格
		createDg();

		// pager
		createPager();

		// 表单
		createFrm();

		function createBagSel() {
			var bagSel = $('#bagSel');
			var bags = window.bags;

			bagSel.combobox('loadData', bags);

			bagSel.combobox('select', -1);

		};

		function createStatusSel() {
			var statusSel = $('#statusSel');
			var data = [{
				value: 1,
				text: '激活'
			}, {
				value: 0,
				text: '冻结'
			}];
			statusSel.combobox('loadData', data);
			statusSel.combobox('select', 1);
		}


		function createDg() {
			var dg = $('#dg');
			dg.datagrid({
				striped: true,
				singleSelect: true,
				fitColumns: true,
				columns: [
					[{
						field: 'id',
						title: '编号',
						width: 50
					}, {
						field: 'bagId',
						title: '标签包',
						width: 80,
						formatter: function(value, row, index) {
							var bags = window.bags;
							return JSLINQ(bags).First(function(c) {
								return c.value == value;
							}).text;
						}
					}, {
						field: 'name',
						title: '标签',
						width: 120,
						formatter: function(value, row, index) {
							var color = row.status ? 'steelblue' : 'gray';
							return ['<span style="color:', color, ';">', value, '</span>'].join('');
						}
					}, {
						field: 'count',
						title: '热度',
						width: 80,
						formatter: function(value, row, index) {
							var interval = [
								[10, 'gray'],
								[80, 'steelblue'],
								[200, 'olive']
							];
							var color = 'red';
							$.each(interval, function(i, n) {
								if(value <= n[0]) {
									color = n[1];
									return false;
								}
							});
							return ['<span style="color:', color, ';">', value, '</span>'].join('');
						}

					}, {
						field: 'dt',
						title: '上传时间',
						width: 120
					}, {
						field: 'editor',
						title: '编辑',
						width: 100
					}]
				]
			});

		}

		function createPager() {
			var pager = $('#pager');
			pager.pagination({
				pageNumber: 1,
				pageSize: 12

			});
		}

		function createFrm() {


			// bag
			createBagSel();
			// status
			createStatusSel();

			function createBagSel() {
				var bagSel = $('#frmBagSel');
				var bags = window.bags;
				bags = format(bags);
				bagSel.combobox('loadData', bags);

				bagSel.combobox('select', -1);

				function format(bags) {
					var rst = JSLINQ(bags).Where(function(c) {
						return c.value != -1;
					}).ToArray();
					return rst;
				}

			}

			function createStatusSel() {
				var statusSel = $('#frmStatusSel');
				var data = [{
					value: 1,
					text: '激活'
				}, {
					value: 0,
					text: '冻结'
				}];
				statusSel.combobox('loadData', data);
				statusSel.combobox('select', 1);
			}
		}
	}



	function attach() {
		// 按钮
		attachSearchBtn();

		// 表格
		attachDg();

		// pager
		attachPager();

		// 表单
		attachFrm();

		function attachDg() {
			var dg = $('#dg');
			dg.datagrid({
				'onClickRow': function(rowIndex, rowData) {
					console.log('onClickRow');
					frm.setData(rowData.id);
					$('#opDist').panel('expand');
					$('#frmToolbar a[ptag="edit"]').trigger('click');
				}
			});
		}


		function attachSearchBtn() {
			var searchBtn = $('#searchBtn');
			searchBtn.bind('click', function(e) {
				proxy.getData();
			});
		}

		function attachPager() {
			var pager = $('#pager');
			pager.pagination({
				onSelectPage: function(pageNumber, pageSize) {
					console.log(pageNumber, pageSize);
					proxy.getData();
				},
				onRefresh: function() {
					proxy.getData();
				}
			});
		}

		function attachFrm() {
			$('#frmToolbar a').click(function(e) {
				// alert($(this).text());
				var ptag = $(this).attr('ptag');
				var dic = {
					"add": function() {
						var trs = $('#opDist tr');
						trs.show();
						trs.filter('[ptag="id"],[ptag="status"]').hide();
						$('#frmTagIdTb').prop('disabled', true);
						$('#frmBagSel').combobox('enable');
						$('#frmTagNameTb').prop('disabled', false);
						$('#frmStatusSel').combobox('disable');
						frm._mode = 'add';
					},
					"edit": function() {
						var trs = $('#opDist tr');
						trs.show();
						$('#frmTagIdTb').prop('disabled', true);
						$('#frmBagSel').combobox('disable');
						$('#frmTagNameTb').prop('disabled', true);
						$('#frmStatusSel').combobox('enable');
						frm._mode = 'edit';
					},
					"remove": function() {
						var trs = $('#opDist tr');
						trs.show();
						$('#frmTagIdTb').prop('disabled', true);
						$('#frmBagSel').combobox('disable');
						$('#frmTagNameTb').prop('disabled', true);
						$('#frmStatusSel').combobox('disable');
						frm._mode = 'remove';
					}
				};
				dic[ptag] && dic[ptag]();
			});

			// ok btn
			$('#frmToolbarSec a').click(function(e) {
				var ptag = $(this).attr('ptag');
				var dic = {
					"ok": function() {
						var mode = frm._mode;
						var dic = {
							'add': function(data) {
								var url = g.serviceUrl;
								var params = $.extend({
									op: 'insertTag'
								}, data);

								var callback = function(data) {
										if(data.flag) {
											proxy.getData();
										} else {
											$.messager.alert('Remote Err', data.msg);
										}
									};
								$.post(url, params, callback);
							},
							'edit': function(data) {
								var url = g.serviceUrl;
								var params = $.extend({
									op: 'editTag'
								}, data);
								var callback = function(data) {
										if(data.flag) {
											proxy.getData();
										} else {
											$.messager.alert('Remote Err', data.msg);
										}
									};
								$.post(url, params, callback);
							},
							'remove': function(data) {
								var url = g.serviceUrl;
								var params = $.extend({
									op: 'deleteTag'
								}, data);
								var callback = function(data) {
										if(data.flag) {
											proxy.getData();
										} else {
											$.messager.alert('Remote Err', data.msg);
										}
									};
								$.post(url, params, callback);
							}
						};
						if(dic[mode]) {
							var data = frm.getData();
							// simple formatter 
							data.tagId = data.id;
							if(frm.check(data)) {
								dic[mode](data);
							} else {
								$.messager.alert('Warn', '参数检测错误!!');
							}
						}
					}
				};
				dic[ptag] && dic[ptag]();
			});
		}
	}

	function first() {
		var searchBtn = $('#searchBtn');
		searchBtn.trigger('click');
	}
}

function getParams() {
	// bagIds
	var bagSel = $('#bagSel');
	var bagIds = bagSel.combobox('getValue') == -1 ? '' : bagSel.combobox('getValue');

	// status
	var statusSel = $('#statusSel');
	var status = statusSel.combobox('getValue');

	// pager
	var pager = $('#pager');
	var pagerOpts = pager.pagination('options');
	var pageIndex = pagerOpts.pageNumber - 1;
	var pageSize = pagerOpts.pageSize;

	return {
		bagIds: bagIds,
		op: 'getTagsForAdmin',
		status: status,
		pageSize: pageSize,
		pageIndex: pageIndex
	};
}


function getData(params, next) {

	var url = g.serviceUrl;
	var data = params;


	var callback = function(d) {

			if(!d.flag) {
				alert(d.msg);
			} else {
				g.dgData = d;
				next && next(d.data);
			}
		};
	$.post(url, data, callback);



}

function disp(data) {
	var dg = $('#dg');


	var total = data[1];
	var rows = format(data[0]);
	dg.datagrid('loadData', {
		total: total,
		rows: rows
	});

	// 格式化数据

	function format(data) {
		var rst = [];
		$.each(data, function(i, n) {
			item = $.extend({}, n);
			item.dt = parseDt(n.dt);
			rst.push(item);
		});
		return rst;

		function parseDt(dt) {
			var num = (dt.match(/\d+/)[0])-0;
			var time = new Date(num);
			console.log(time);
			return time.toString('yyyy年MM月dd日');
		}
	}
}

function setPager(data) {
	var pager = $('#pager');
	var total = data[1];
	var opts = pager.pagination('options');
	var pageIndex = Math.min(opts.pageNumber, total) - 1;
	pager.pagination({
		total: total,
		pageNumber: pageIndex + 1
	});
}


// 通过id在form中展示数据
var frm = {
	setData: function(data) {
		if(typeof(data) == "number") {
			data = JSLINQ(g.dgData.data[0]).First(function(c) {
				return c.id == data;
			});

		}
		if(data) {
			$('#frmTagIdTb').val(data.id);
			$('#frmBagSel').combobox('select', data.bagId);
			$('#frmTagNameTb').val(data.name);
			$('#frmStatusSel').combobox('select', data.status);
		}
	},
	getData: function() {
		var rst = {};
		rst.id = $('#frmTagIdTb').val();
		rst.bagId = $('#frmBagSel').combobox('getValue');
		rst.name = $('#frmTagNameTb').val();
		rst.status = $('#frmStatusSel').combobox('getValue');
		rst.mode = this._mode;
		return rst;
	},
	check: function() {
		var rst = false;
		var data = this.getData();
		var dic = {
			'add': function(data) {
				return data.name != "";
			},
			'edit': function(data) {
				return data.id != "" && data.id != -1;
			},
			'remove': function(data) {
				return data.id != "" && data.id != -1;
			}
		};
		if(this._mode && dic[this._mode]) {
			rst = dic[this._mode](data);
		}
		return rst;
	},
	_mode: null
};


// 预加载数据

function preload(loadFn) {
	var list = {};
	// getBags
	list.bags = function(next, name) {
		var url = '../../service/tagerOp.ashx';
		var data = {
			op: 'getBags',
			keyWord: '',
			pageSize: 10000,
			pageIndex: 0
		};
		var callback = function(d) {
				if(d.flag) {
					var fdata = format(d.data);
					next && next(fdata, name);
				} else {
					alert(d.msg);
				}
			};
		$.post(url, data, callback);

		// format

		function format(data) {
			var rst = [{
				value: -1,
				text: '全部'
			}];
			$.each(data[0], function(i, n) {
				rst.push({
					value: n.id,
					text: n.name
				});
			})
			rst = rst.sort(function(a, b) {
				return a.id - b.id;
			});
			return rst;
		}
	};


	for(var li in list) {
		var fi = list[li];
		fi(next, li);
	}
	return list;

	function next(data, name) {
		window[name] = data;
		var flag = true;
		for(var li in list) {
			if(!window[li]) {
				flag = false;
				break;
			}
		}
		flag && loadFn();
	}

}

var g = {
	//dgData
	serviceUrl: '../../service/tagerOp.ashx'
};

// 代理者
var proxy = {
	getData: function() {
		var params = getParams();
		console.log(params);
		getData(params, function(data) {
			disp(data);
			setPager(data);
		});
	}

};